package com.scaffold.springmvc.util.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * servlet3.0默认是不支持异步的通过asyncSupported=true,打开
 * 
 */
@WebServlet(name = "SecondServlet", urlPatterns = { "/secondServlet" }, asyncSupported = true)
public class SecondServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = null;
		resp.setContentType("text/html");
		try {
			out = resp.getWriter();
			out.print("servlets starts:" + new Date() + "<br>");
			out.flush();
			AsyncContext asyncContext = req.startAsync();
			/**
			 * AsyncListener为什么没有适配器呢？需要各个厂家实现？
			 */
			asyncContext.addListener(new AsyncListener() {
				public void onComplete(AsyncEvent asyncEvent)
						throws IOException {
					// 将流在这里关闭
					asyncEvent.getSuppliedResponse().getWriter().close();
					System.out.println("asynContext finished....");
				}
				public void onError(AsyncEvent arg0) throws IOException {
					// TODO Auto-generated method stub
				}
				public void onStartAsync(AsyncEvent arg0) throws IOException {
					// TODO Auto-generated method stub
				}
				public void onTimeout(AsyncEvent arg0) throws IOException {
					// TODO Auto-generated method stub
				}
			});
			new Thread(new MyThread(asyncContext)).start();
			out.print("servlets ends:" + new Date() + "<br>");
			out.flush();
		} finally {
			/**
			 * 一开是在这里关闭了,关了,后面就用不成了 :）
			 * 
			 */
			/*
			 * if(null != out){ out.close(); out = null; }
			 */
		}

	}
}